<?php
/***************************************************************
*  Copyright notice
*
*  (c) 2008 Starbugs <univis2typo3@googlegroups.com>
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/

require_once(PATH_tslib.'class.tslib_pibase.php');


/**
 * Plugin 'publications' for the 'univis2typo3' extension.
 *
 * @author	Starbugs <univis2typo3@googlegroups.com>
 * @package	TYPO3
 * @subpackage	tx_univis2typo3
 */
class tx_univis2typo3_pi2 extends tslib_pibase {
	var $prefixId      = 'tx_univis2typo3_pi2';		// Same as class name
	var $scriptRelPath = 'pi2/class.tx_univis2typo3_pi2.php';	// Path to this script relative to the extension dir.
	var $extKey        = 'univis2typo3';	// The extension key.
	var $pi_checkCHash = true;
	var $department = "";
	var $template = "";
	var $cObj = "";

	/**
	 * The main method of the PlugIn
	 *
	 * @param	string		$content: The PlugIn content
	 * @param	array		$conf: The PlugIn configuration
	 * @return	The content that is displayed on the website
	 */

	function main($content, $conf)	{
		$this->conf = $conf;
		$this->pi_setPiVarDefaults();
		$this->pi_loadLL();
		$this->department = $this->conf['department_id'];

		$templateCode = $this->cObj->fileResource($this->conf['templateFile']);
		$this->template = $this->cObj->getSubpart($templateCode,"###TEMPLATE_PUBLICATIONS###");

		// Flex-Form initialisieren
		$this->pi_initPIflexForm();	
		$content = $this->getContent($this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'what_to_display', 'sDEF'));
		return $this->pi_wrapInBaseClass($content);
	}

	// Function returns result for a single publication key
	function getPublication($pub_key){
		return $this->getItems("", "", $pub_key, "");
		
	}

	// Function returns results for an project keys
	function getGroupPublications($group_uid){
	
		$project_keys = array();
		
		$select 	= 'project_key' ;
		$from 		= 'tx_u2t3_group_projects';
		$where		= 'group_uid = "'.$group_uid.'"';
		$orderby	= '';
		$limit 	= '';
		$query = $GLOBALS['TYPO3_DB']->SELECTquery(
			$select,
			$from,
			$where,
			$groupby,
			$orderby,
			$limit
		);


		$items = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
		while ($item = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($items))
		{
		    $project_keys[] = $item['project_key'];
		}

				
		$pub_keys = array();


		// get all pub keys for each project		
		FOREACH ($project_keys AS $projkey)
		{
		    $select 	= 'public' ;
		    $from 	= 'u_research_publics';
		    $where	= 'project_key = "'.$projkey.'"';
		    $orderby	= '';
		    $limit 	= '';
		    $query = $GLOBALS['TYPO3_DB']->SELECTquery(
			    $select,
			    $from,
			    $where,
			    $groupby,
			    $orderby,
			    $limit
		    );

		    $items = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
		    while ($item = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($items))
		    {
			$pub_keys[] = $item['public'];
		    }
		}

		return $this->getItems("", "", "", $pub_keys);
	}

	// Function returns results for an project keys
	function getProjectPublications($project_key){
				
		$pub_keys = array();
		//get pub_keys for the given project_key from table tx_u2t3_research_public and store it in array pub_keys
		//using function getPublications returns then all publications, this might be not well performing
		
		$select 	= 'public' ;
		$from 		= 'u_research_publics';
		$where		= 'project_key = "'.$project_key.'"';
		$orderby	= '';
		$limit 	= '';
		$query = $GLOBALS['TYPO3_DB']->SELECTquery(
			$select,
			$from,
			$where,
			$groupby,
			$orderby,
			$limit
		);

		$items = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
		while ($item = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($items))
		{
		    $pub_keys[] = $item['public'];
		}

		return $this->getItems("", "", "", $pub_keys);
	}

	// Function returns result for an array of publication keys
	function getPublications($pub_keys){
		return $this->getItems("", "", "", $pub_keys);
	}

	function getNitems($year = "", $authorKey = "", $maxNumber){
		return $this->getItems($year, $authorKey, "", "", $maxNumber);
	}
    
	function getItems($year = "", $authorKey = "", $pub_key = "", $pub_keys = "", $maxNumber = "") {
		$select 	=" * , 
				    CONCAT(
					(
					    CASE WHEN (`testSQL`.`conf_url` IS NULL) OR (`testSQL`.`conf_url` = '') THEN
					    ( testSQL.`conference`)
					    ELSE
					    ( CONCAT( '<a href=\"', `testSQL`.`conf_url`, '\">', `testSQL`.`conference`, '</a>' ))
					    END
					)
				    ) AS conf_link,
				    CONCAT(
					    (
						    CASE WHEN (`testSQL`.`puburl` IS NULL) OR (`testSQL`.`puburl` = '') THEN
						    ( testSQL.`pubtitle`)
						    ELSE
						    ( CONCAT( '<a href=\"', `testSQL`.`puburl`, '\">', `testSQL`.`pubtitle`, '</a>' ))
						    END
					    )
				    ) AS pub_link ";
		$from 		=" (
				    SELECT 
					`T4` . * , 
					`T1`.`authors` AS `authors` , 
					`T1`.`author_keys` AS `author_keys` , 
					`T2`.`editors` AS `editors` , 
					`T6`.`description` AS `description` , 
					`T6`.`description_en` AS `description_en`
				    FROM (
					SELECT 
					    `T3`.`key` AS `key` , 
					    `T3`.`pubtitle` AS `pubtitle` , 
					    `T3`.`address` AS `address` , 
					    `T3`.`booktitle` AS `booktitle` , 
					    `T3`.`conf_url` AS `conf_url` , 
					    `T3`.`conference` AS `conference` , 
					    `T3`.`edition` AS `edition` , 
					    `T3`.`hstype` AS `hstype` , 
					    `T3`.`hsyear` AS `hsyear` , 
					    `T3`.`id` AS `id` , 
					    `T3`.`isbn` AS `isbn` , 
					    `T3`.`issn` AS `issn` , 
					    `T3`.`journal` AS `journal` , 
					    `T3`.`keywords` AS `keywords` , 
					    `T3`.`number` AS `number` , 
					    `T3`.`pages` AS `pages` , 
					    `T3`.`plocation` AS `plocation` , 
					    `T3`.`publisher` AS `publisher` , 
					    `T3`.`puburl` AS `puburl` , 
					    `T3`.`school` AS `school` , 
					    `T3`.`series` AS `series` , 
					    `T3`.`servolume` AS `servolume` , 
					    `T3`.`type` AS `type` , 
					    `T3`.`volume` AS `volume` , 
					    `T3`.`year` AS `year`
					FROM 
					    `tx_u2t3_pub` AS `T3`
					WHERE ";
		if($year != "") {
			$from .="`T3`.`year` = ".$year." AND ";
		}

		if($pub_key != "") {
			$from .="`T3`.`key` = '".$pub_key."' AND ";
		}

		if($pub_keys != "") {
			$from .= "`T3`.`key` IN ('".implode("','", $pub_keys)."') AND ";
		}
		$from .="`T3`.department_id = ".$this->department."
				    ) 
					AS `T4`
				    JOIN `tx_u2t3_pub_view_authors` AS `T1` ON `T4`.`key` = `T1`.`pub_key`
				    LEFT JOIN `tx_u2t3_pub_view_editors` AS `T2` ON `T1`.`pub_key` = `T2`.`pub_key`
				    JOIN `tx_u2t3_pub_type_order` AS `T6` ON `T6`.`type` = `T4`.`type`";
		if ($authorKey != "") {
			$from .="   WHERE 
					`T1`.`author_keys` LIKE '%{$authorKey}%'";
		}
		$from .= " ORDER BY `T4`.`year` DESC , `T6`.sorting
				    ) 
					AS testSQL ";
		$where		= "";

		$orderby	= " testSQL.year DESC ";

		if ('' != $maxNumber) $limit = $maxNumber;

		$query = $GLOBALS['TYPO3_DB']->SELECTquery(
			$select,
			$from,
			$where,
			$groupby,
			$orderby,
			$limit
		);

		//print $query; die();

		return $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
	}

	function fillPublicationmarker($arrMarker, $row) {
	    $pubText = '';
	    switch ($row['type']) {
		case 'arttagu':
		    $pub_conference	= "";
		    if ($row['booktitle'])
			    $pub_conference	.= $row['booktitle'];	

		    if ($row['conference'])
		    {
			    $pub_conference	.= " (".$row['conf_link'];
			    if ($row['address'])
				    $pub_conference .= " ".htmlentities($row['address']);
			    if ($row['hsyear'])
				    $pub_conference .= " ".htmlentities($row['hsyear']).") ";
		    }
		    if ($row['volume'])
			    $pub_conference .= " Vol. ".$row['volume'];
		    if ($row['plocation'])
			    $pub_conference .= " ".$row['plocation'];
		    if ($row['publisher'])
			    $pub_conference .= " : ".$row['publisher'];
		    if ($row['year'])
			    $pub_conference .= " ".$row['year'];
		    if ($row['pages'])
			    $pub_conference .= ", pp. ".$row['pages'];
		    if ($row['isbn'])
			    $pub_conference .= " - ISBN ".$row['isbn'];

		    $pubText = $pub_conference;
		    break;
		case 'artzeit':
		    $pub_journal = "";
		    if ($row['journal'])
			    $pub_journal .= "In: ".$row['journal'];
		    if ($row['volume'])
			    $pub_journal .= " ".$row['volume'];
		    if ($row['year'])
			    $pub_journal .= " (".$row['year'].")";
		    if ($row['number'])
			    $pub_journal .= " No. ".$row['number'];
		    if ($row['pages'])
			    $pub_journal .= " pp. ".$row['pages'];
		    $pubText = htmlentities($pub_journal);
		    break;
		case 'techrep':
		    $pub_technical = "";
		    $pub_technical .= "Technical Report";
		    if ($row['school'])
			    $pub_technical .= ": ".$row['school'];
		    if ($row['address'])
			    $pub_technical .= ", ".$row['address'];
		    if ($row['year'])
			    $pub_technical .= ", ".$row['year'];
		    $pubText = htmlentities($pub_technical);
		    break;
		case 'artmono':
		    $pub_mono = "";
		    if ($row['booktitle'])
			    $pub_mono .= $row['booktitle'];
		    if ($row['series'])
			    $pub_mono .= " ".$row['series'];
		    if ($row['plocation'])
			    $pub_mono .= " ".$row['plocation'];
		    if ($row['publisher'])
			    $pub_mono .= ": ".$row['publisher'];
		    if ($row['year'])
			    $pub_mono .= ", ".$row['year'];
		    if ($row['pages'])
			    $pub_mono .= ", ".$row['pages'];
		    $pubText = htmlentities($pub_mono);
		    break;
		case 'tagband':
		    $pub_tagband = "";
		    if ($row['conference'])
			    $pub_tagband .= $row['conference'];
		    if ($row['address'])
			    $pub_tagband .= ", ".$row['address'];
		    if ($row['volume'])
			    $pub_tagband .= " Vol.:".$row['volume'];
		    if ($row['publisher'])
			    $pub_tagband .= ", ".$row['publisher'];
		    if ($row['year'])
			    $pub_tagband .= ", ".$row['year'];
		    $pubText = htmlentities($pub_tagband);
		    break;
		case 'tagung':
		    $pub_tagung = "";
		    if ($row['conference'])
			    $pub_tagung .= $row['conference'];
		    if ($row['address'])
			    $pub_tagung .= ", ".$row['address'];
		    if ($row['volume'])
			    $pub_tagung .= " Vol.:".$row['volume'];
		    if ($row['year'])
			    $pub_tagung .= ", ".$row['year'];
		    $pubText = htmlentities($pub_tagung);
		    break;
		case 'talk':
		    $pub_talk = "";
		    if ($row['school'])
			    $pub_talk .= "at ".$row['school'];
		    if ($row['conference'])
			    $pub_talk .= " (".$row['conference'].")";
		    $pubText = htmlentities($pub_talk);
		    break;
		case 'monogr':
		    $pub_monogr = "";
		    if ($row['plocation'])
			    $pub_monogr .= " ".$row['plocation'];
		    if ($row['publisher'])
			    $pub_monogr .= ": ".$row['publisher'];
		    if ($row['year'])
			    $pub_monogr .= ", ".$row['year'];
		    $pubText = htmlentities($pub_monogr);
		    break;
		case 'hschri':
		    $pub_hschri = "";
    		if ($row['year'])
			    $pub_hschri .= "(".$row['year'].") ";
		    if ($row['pages'])
			    $pub_hschri .= $row['pages']. " pages";
		    $pubText = htmlentities($pub_hschri);
		    break;
		case 'schutzr':
		    $pub_schutzr = "";
			if ($row['number'])
				$pub_schutzr .= " ".$row['number'];
			$pubText = htmlentities($pub_schutzr);
			break; 

		default:
		    $pubText = '';
		    break;
	    }
	    $arrMarker["###TEMPLATE_PUBLICATIONS_CONFERENCE###"] =& $pubText;


	    $arrMarker["###TEMPLATE_PUBLICATIONS_ID###"] =  $row['id'];
	    $arrMarker["###TEMPLATE_PUBLICATIONS_AUTHORS###"] =  $row['authors'];
	    $arrMarker["###TEMPLATE_PUBLICATIONS_TITLE###"] = $row['pub_link'];

	    if ($row['editors'])
		    $arrMarker["###TEMPLATE_PUBLICATIONS_EDITORIAL###"] = 'In: <span class="editors">'.$row['editors'].'</span> (Eds.)';
	    else
		    $arrMarker["###TEMPLATE_PUBLICATIONS_EDITORIAL###"] = "";					

		$linkPDF = '';
	    $arrMarker['###TEMPLATE_PUBLICATIONS_TYPE###'] = $row['type'];
	    $arrMarker['###TEMPLATE_PUBLICATIONS_YEAR###'] = $row['year'];
	    //Check for pdf in download link
	    //If download link equals pdf then link symbol
	    if (!$row['puburl']) {
		$arrMarker['###TEMPLATE_PUBLICATIONS_PDF_DOWNLOAD###'] = '';
	    } else {
		    $fileExt = strtolower( substr($row['puburl'], -3, 3) );

		    $arrMarker['###TEMPLATE_PUBLICATIONS_PDF_DOWNLOAD###'] = '<a href="'.$row['puburl'].'" target="_blank">';
		    if ('pdf' == $fileExt) {
			$arrMarker['###TEMPLATE_PUBLICATIONS_PDF_DOWNLOAD###'] .= '<img src="http://www5.informatik.uni-erlangen.de/images/fileicon-pdf.png" alt="PDF download" width="22" height="22" />';
		    } else {
			//else [link]
			$arrMarker['###TEMPLATE_PUBLICATIONS_PDF_DOWNLOAD###'] .= '<img src="http://www5.informatik.uni-erlangen.de/typo3/sysext/rtehtmlarea/htmlarea/plugins/TYPO3Browsers/img/external_link_new_window.gif" alt="external link" width="14" height="10" />';
		    }
		    $arrMarker['###TEMPLATE_PUBLICATIONS_PDF_DOWNLOAD###'] .= '</a>';
	    }

	    return $arrMarker;
    }

    function getContent($year, $authorKey = null, $maxNumber = null) {
	if ($maxNumber != NULL){
	    $items = $this->getNitems($year, $authorKey, $maxNumber);
	} else {
	    $items = $this->getItems($year, $authorKey);
	}

//	$testGroup = 8;
//	$items = $this->getGroupPublications($testGroup);

	$arrYearMarker                  = array();
	$arrGroupMarker                 = array();
	$arrMarker                      = array();
	$arrWrappedPubYearSubpart       = array();
	$arrWrappedPubTypeSubpart       = array();
	$arrWrappedSubMarker            = array();

	$content_year_item		= "";
	$content_type_item		= "";
	$content_publication_item 	= "";
	$year_dummy 			= "";
	$type_dummy 			= "";
	$description_dummy 		= "";
	$i = 0;

	//Initialize content
	$content = '';

	$language = $GLOBALS["TSFE"]->sys_language_uid;
	if ($language == 0) {
		$description = 'description_en';
	} else {
		$description = 'description';
	}

	//Get first entry
	$row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($items);
	if ( $row['pubtitle'] == '') {
		$content .= ((1 == $language) ? 'Keine Publikationen.' : "No publications, yet.");
		return $content;
	}
	
	// fill temporary year and type
	$year_dummy = $row['year'];
	$type_dummy = $row['type'];
	$description_dummy = $row[$description];
		
	//For all entries
	do{
	    $arrMarker = array();
	    $check_types = false;
	    // check type
	    if ( $type_dummy != $row['type'])
	    {
		//data items with the same type are finished
		//set content
		$arrWrappedSubMarker['###TEMPLATE_PUBLICATIONS_ITEM###'] = $content_publication_item;
		//set publication type
		$arrWrappedSubMarker['###TEMPLATE_PUBLICATIONS_TYPE###'] = htmlentities($description_dummy);

		$content_type_item .= $this->cObj->substituteMarkerArrayCached(
				$this->cObj->getSubpart($this->template,"###TEMPLATE_PUBLICATIONS_GROUP_TYPE###"),
				$arrMarker,
				$arrWrappedSubMarker);
		//set new type_dummy	
		$type_dummy = $row['type'];
		$description_dummy = $row[$description];

		//initialize content_publication_item
		$content_publication_item = '';
		$check_types = true;
	    }

	    // check year
	    if ( $year_dummy != $row['year'] )
	    {
		if($check_types == false) {
			//data items with the same type are finished
			//set content
			$arrWrappedSubMarker['###TEMPLATE_PUBLICATIONS_ITEM###'] = $content_publication_item;
			//set publication type
			$arrWrappedSubMarker['###TEMPLATE_PUBLICATIONS_TYPE###'] = htmlentities($description_dummy);
	
			$content_type_item .= $this->cObj->substituteMarkerArrayCached(
					$this->cObj->getSubpart($this->template,"###TEMPLATE_PUBLICATIONS_GROUP_TYPE###"),
					$arrMarker,
					$arrWrappedSubMarker);
			//set new type_dummy	
			$type_dummy = $row['type'];
			$description_dummy = $row[$description];
	
			//initialize content_publication_item
			$content_publication_item = '';
			$check_types = true;
		}
		//data items of the same year are finished
		$arrWrappedPubTypeSubpart['###TEMPLATE_PUBLICATIONS_GROUP_TYPE###'] = $content_type_item;
		//set publication year
		$arrWrappedPubTypeSubpart['###TEMPLATE_PUBLICATIONS_YEAR###'] = $year_dummy;
		//set number of publications
		$arrWrappedPubTypeSubpart['###TEMPLATE_PUBLICATIONS_NUM###'] = $i;
		// initialize number of publications per year
		$i = 0;
		$content_year_item .= $this->cObj->substituteMarkerArrayCached(
				$this->cObj->getSubpart($this->template,"###TEMPLATE_PUBLICATIONS_GROUP_YEAR###"),
				$arrWrappedSubMarker,
				$arrWrappedPubTypeSubpart);
	
		//set new year_dummy	
		$year_dummy = $row['year'];
		//initialize content_type_item
		$content_type_item = '';
	    }

	    // Fill publication marker
		$arrMarker = $this->fillPublicationmarker($arrMarker,$row);
	    // increment number of publication for the same year
		$i++;

	    // add publication item to content
		$content_publication_item .= $this->cObj->substituteMarkerArrayCached(
			$this->cObj->getSubpart($this->template,"###TEMPLATE_PUBLICATIONS_ITEM###"),
			$arrMarker);
	} while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($items));

	// every data is processed 
	// finish templates
	//set content
	$arrWrappedSubMarker['###TEMPLATE_PUBLICATIONS_ITEM###'] = $content_publication_item;
	//set publication type
	$arrWrappedSubMarker['###TEMPLATE_PUBLICATIONS_TYPE###'] = htmlentities($description_dummy);

	//replace content out of template with publications of the same type
	$content_type_item .= $this->cObj->substituteMarkerArrayCached(
			$this->cObj->getSubpart($this->template,"###TEMPLATE_PUBLICATIONS_GROUP_TYPE###"),
			$arrMarker,
			$arrWrappedSubMarker);

	//data items of the same year are finished
	$arrWrappedPubTypeSubpart['###TEMPLATE_PUBLICATIONS_GROUP_TYPE###'] = $content_type_item;
	//set publication year
	$arrWrappedPubTypeSubpart['###TEMPLATE_PUBLICATIONS_YEAR###'] = $year_dummy;
	//set number of publications
	$arrWrappedPubTypeSubpart['###TEMPLATE_PUBLICATIONS_NUM###'] = $i;

	$content_year_item .= $this->cObj->substituteMarkerArrayCached(
			$this->cObj->getSubpart($this->template,"###TEMPLATE_PUBLICATIONS_GROUP_YEAR###"),
			$arrWrappedSubMarker,
			$arrWrappedPubTypeSubpart);

	$arrWrappedPubYearSubpart['###TEMPLATE_PUBLICATIONS_GROUP_YEAR###'] = $content_year_item;

	return $this->cObj->substituteMarkerArrayCached(
				$this->template,
				$arrWrappedPubTypeSubpart,
				$arrWrappedPubYearSubpart);
	
	}
}

if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/univis2typo3/pi2/class.tx_univis2typo3_pi2.php'])	{
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/univis2typo3/pi2/class.tx_univis2typo3_pi2.php']);
}

?>
